package com.xp.flower.qsd.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xp.flower.api.ICommentService;
import com.xp.flower.common.ajax.AjaxError;
import com.xp.flower.common.ajax.AjaxResponse;
import com.xp.flower.common.dto.CommentDTO;
import com.xp.flower.common.dto.UserDTO;
import com.xp.flower.qsd.consts.WebConsts;


@Controller
@RequestMapping("commentController")
public class CommentController {
    
    @Autowired
    private ICommentService commentServiceImpl;
    
    @RequestMapping("goToComment")
    public String goToComment(HttpSession session,@RequestParam(value="flowerId",required=true)Long flowerId,Model model)
    {
        List<CommentDTO> commentDTOList = commentServiceImpl.queryFlowerComment(flowerId);
        model.addAttribute("flowerId", flowerId);
        model.addAttribute("commentDTOList", commentDTOList);
        return "qsd/comment";
    }
    
    @RequestMapping("addComment")
    @ResponseBody
    public AjaxResponse<CommentDTO> addComment(HttpSession session,CommentDTO commentDTO) {
        UserDTO userDTO = (UserDTO)session.getAttribute(WebConsts.USERINFO);
        AjaxResponse<CommentDTO> response = null;
        if (null == userDTO) {
            response = new AjaxResponse<CommentDTO>(AjaxError.PLEASELOGIN.getCode(), AjaxError.PLEASELOGIN.getMessage());
        } else {
            commentDTO.setUserId(userDTO.getId());
            commentDTO.setCreatetime(System.currentTimeMillis());
            Integer result = commentServiceImpl.insertComment(commentDTO);
            if(result > 0){
                response = new AjaxResponse<CommentDTO>(AjaxError.SUBMITCOMMENTSUCCESS.getCode(), AjaxError.SUBMITCOMMENTSUCCESS.getMessage());
            }else{
                response = new AjaxResponse<CommentDTO>(AjaxError.SUBMITCOMMENTFAIL.getCode(), AjaxError.SUBMITCOMMENTFAIL.getMessage());
            }
        }
        return response;
    }

}
